﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;
using System.IO;
using System.Text;

namespace HealthCommunity.Controls
{
	public partial class UCCourseWareList : System.Web.UI.UserControl
	{
		private ICourseProvider _CourseProvider;

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindCourseWare();

			btnDeleteSelected.Visible = false;
			hlCreateCourseWare.Visible = false;

			var u = SiteContext.Current.CurrentUser;

			if(u != null && u.Role != null)
			{
				btnDeleteSelected.Visible = u.Role.RoleName.ToLower().Equals("admin") || u.Role.RoleName.ToLower().Equals("storemanager") || u.Role.RoleName.ToLower().Equals("storeadmin");
				hlCreateCourseWare.Visible = u.Role.RoleName.ToLower().Equals("admin") || u.Role.RoleName.ToLower().Equals("storemanager") || u.Role.RoleName.ToLower().Equals("storeadmin");
			}
		}

		protected void gvCourseWare_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if(e.CommandName.Equals("download"))
			{
				var courseWareID = int.Parse(e.CommandArgument.ToString());

				if(_CourseProvider == null)
				{
					_CourseProvider = new CourseProvider();
				}

				var theCourseWare = _CourseProvider.GetCourseWare(courseWareID);

				if(theCourseWare != null)
				{
					if(DownloadCourseWare(theCourseWare))
					{
						var user = SiteContext.Current.CurrentUser;

						theCourseWare.DownloadCount = theCourseWare.DownloadCount.GetValueOrDefault(0) + 1;

						_CourseProvider.UpdateCourseWare(theCourseWare);

						Response.End();
					}
				}
			}
		}

		private bool DownloadCourseWare(CourseWare theCourseWare)
		{
			if(theCourseWare != null && !string.IsNullOrEmpty(theCourseWare.CourseWarePath))
			{
				if(SiteContext.Current.CurrentUser != null)
				{
					var cwPathPart = theCourseWare.CourseWarePath.Split('\\');
					var fileName = cwPathPart[cwPathPart.Length - 1];
					var newFileName = string.Format("{0}.{1}", theCourseWare.CourseWareName, fileName.Split('.')[1]);
					var filePath = Server.MapPath("~/Document");
					FileInfo fileInfo = new FileInfo(theCourseWare.CourseWarePath);

					if(fileInfo.Exists)
					{
						FileStream fs = new FileStream(theCourseWare.CourseWarePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
						BinaryReader br = new BinaryReader(fs);

						try
						{
							long startBytes = 0;
							string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
							string _EncodedData = HttpUtility.UrlEncode(newFileName, Encoding.UTF8) + lastUpdateTiemStamp;

							Response.Clear();
							Response.Buffer = false;
							Response.AddHeader("Accept-Ranges", "bytes");
							Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
							Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
							Response.ContentType = "application/octet-stream";
							Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8));
							Response.AddHeader("Content-Length", (fileInfo.Length - startBytes).ToString());
							Response.AddHeader("Connection", "Keep-Alive");
							Response.ContentEncoding = Encoding.UTF8;

							//Send data
							br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

							//Dividing the data in 1024 bytes package
							int maxCount = (int)Math.Ceiling((fileInfo.Length - startBytes + 0.0) / 1024);

							//Download in block of 1024 bytes
							int i;
							for(i = 0; i < maxCount && Response.IsClientConnected; i++)
							{
								Response.BinaryWrite(br.ReadBytes(1024));
								Response.Flush();
							}
							//if blocks transfered not equals total number of blocks
							if(i < maxCount)
							{
								return false;
							}

							return true;
						}
						catch
						{
							return false;
						}
						finally
						{
							br.Close();
							fs.Close();
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}

		protected void gvCourseWare_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if(e.Row.DataItem != null)
			{
				var dataItem = e.Row.DataItem as CourseWare;

				var hfCourseWareID = e.Row.FindControl("hfCourseWareID") as HiddenField;
				var lbtnDownload = e.Row.FindControl("lbtnDownload") as LinkButton;
				var hlCourseWareName = e.Row.FindControl("hlCourseWareName") as HyperLink;

				hfCourseWareID.Value = dataItem.CourseWareID.ToString();
				lbtnDownload.CommandArgument = dataItem.CourseWareID.ToString();
				hlCourseWareName.Text = dataItem.CourseWareName;

				if(!string.IsNullOrEmpty(dataItem.CourseWarePath))
				{
					var p = dataItem.CourseWarePath.Split('\\');
					var key = string.Empty;
					if(p != null && p.Length > 0)
					{
						key = p[p.Length - 1];
					}
					hlCourseWareName.NavigateUrl = "~/DocumentViewer.aspx?key=" + key;
				}
			}
		}

		protected void btnDeleteSelected_Click(object sender, EventArgs e)
		{
			List<int> ids = new List<int>();
			List<string> paths = new List<string>();

			if(_CourseProvider == null)
			{
				_CourseProvider = new CourseProvider();
			}

			foreach(GridViewRow row in gvCourseWare.Rows)
			{
				var chbCourseWare = row.FindControl("chbCourseWare") as CheckBox;

				if(chbCourseWare.Checked)
				{
					var hfCourseWareID = row.FindControl("hfCourseWareID") as HiddenField;

					var id = 0;

					if(int.TryParse(hfCourseWareID.Value, out id))
					{
						ids.Add(id);
					}

					if(id > 0)
					{
						var theCourseWare = _CourseProvider.GetCourseWare(id);
						if(theCourseWare != null && !string.IsNullOrEmpty(theCourseWare.CourseWarePath))
						{
							paths.Add(theCourseWare.CourseWarePath);
						}
					}
				}
			}

			if(ids.Count > 0)
			{
				if(_CourseProvider.DeleteCourseWare(ids))
				{
					//BindCourseWare();
				}
			}

			if(paths.Count > 0)
			{
				foreach(var p in paths)
				{
					if(File.Exists(p))
					{
						File.Delete(p);
					}
				}
			}
		}

		private void BindCourseWare()
		{
			var user = SiteContext.Current.CurrentUser;

			if(user != null && user.Role.RoleName.ToLower().Equals("admin"))
			{
				var drugStore = SiteContext.Current.CurrentDrugStore;

				if(drugStore != null)
				{
					if(_CourseProvider == null)
					{
						_CourseProvider = new CourseProvider();
					}

					gvCourseWare.DataSource = _CourseProvider.GetAllCourseWare(drugStore.DrugStoreID);
					gvCourseWare.DataBind();
				}
			}
			else
			{
				if(user != null && user.DrugStoreID.GetValueOrDefault(0) > 0)
				{
					if(_CourseProvider == null)
					{
						_CourseProvider = new CourseProvider();
					}

					gvCourseWare.DataSource = _CourseProvider.GetAllCourseWare(user.UserID, user.DrugStoreID.Value);
					gvCourseWare.DataBind();
				}
			}
		}
	}
}